import Vue from 'vue'
import VueRouter from 'vue-router'
// 一级路由
import Login from '@/views/Login'
import Register from '@/views/Register'
import Detail from '@/views/Detail'
import Layout from '@/views/Layout'
// 二级路由
import Like from '@/views/Like'
import Article from '@/views/Article'
import Collect from '@/views/Collect'
import User from '@/views/User'
import { getToken } from '@/utils/storage'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    { path: '/register', component: Register },
    { path: '/article/:id', component: Detail },
    {
      path: '/',
      component: Layout,
      redirect: '/article',
      children: [
        { path: 'article', component: Article },
        { path: 'like', component: Like },
        { path: 'collect', component: Collect },
        { path: 'user', component: User }
      ]
    }
  ]
})
// 白名单
const whiteList = ['/login', '/register']
/**
 * 配置路由的全局前置首位
 * to 往哪里去。 到哪去的路由信息对象
 * from 从哪来。 从哪来的路由信息对象
 * next（）是否放行 如果next调用，则放行 / next（路径）拦截某个路径页面
 */
router.beforeEach((to, from, next) => {
  // console.log('到哪里去', to)
  // console.log('从哪里来', from)
  const token = getToken()
  if (token) {
    if (to.path === '/login' || to.path === '/register') {
      next('/')
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
